/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.skatiger.jrove.spring.form.renderer;

import java.beans.PropertyEditor;
import java.io.IOException;

import org.skatiger.jrove.JroveException;
import org.skatiger.jrove.ResponseWriter;
import org.skatiger.jrove.ViewContext;
import org.skatiger.jrove.component.UIComponent;
import org.skatiger.jrove.renderer.Html;
import org.skatiger.jrove.spring.utils.ValueFormatter;
import org.springframework.web.servlet.support.BindStatus;

public class InputSingleCheckedRenderer extends AbstractInputElementRenderer {
    protected static final String OPTION_SELECTED_PROPERTY_NAME = "optionSelected";

    @Override
    protected void renderValueAttribute(ViewContext context,
            UIComponent component) throws IOException {
        renderFromValue(context, component);
    }

    /**
    * Render the '<code>input(checkbox)</code>' with the supplied value, marking the
    * '<code>input</code>' element as 'checked' if the supplied value matches the
    * bound value.
    */
    protected void renderFromValue(ViewContext context, UIComponent component)
            throws IOException {
        ResponseWriter writer = context.getResponseWriter();
        Object value = component.getAttributes().get(Html.VALUE_ATTR);
        if (value == null) {
            throw new IllegalArgumentException(
                    "Attribute 'value' is required when binding to non-boolean values");
        }
        writer.writeAttribute(Html.VALUE_ATTR,
                convertToDisplayString(component, value), Html.VALUE_ATTR);
        boolean isChecked = SelectedValueComparator.isSelected(
                getBindStatus(component), value);
        //render checked attribute
        writer.writeAttribute(Html.CHECKED_ATTR, isChecked, Html.VALUE_ATTR);
    }

    protected String convertToDisplayString(UIComponent component, Object value)
            throws JroveException {
        BindStatus bindStatus = getBindStatus(component);
        PropertyEditor editor = (value != null ? bindStatus.findEditor(value
                .getClass()) : null);
        boolean htmlEscape = isHtmlEscape(component);

        return ValueFormatter.getDisplayString(value, editor, htmlEscape);
    }
}
